<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/9 0009
 * Time: 14:10
 */

namespace logic\yuding\driver;
use core\Msg;
use logic\LogicException;
use api\Checkapi;
use logic\Wechat;
use mod\CheckTicket;

class Travel extends Base
{
	public function pc( $data = array() , $userInfo = array() )
	{
		$this -> setSource( 'pc' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );
		$this -> checkLianpiao();
		$this -> checkPihao();
		$this -> checkPihaoTime();
		$this -> checkTravel();
		$this -> checkZuhesp();
		$yudingData = $this -> checkYuding();
		$operaData = $this->opera($yudingData);
		if( !$operaData ){
			throw new LogicException('预订失败，请稍后重试');
		}
		$this->sendCheck( $yudingData['data'] );
		$this->sms();
		$this->addRecord();
	}

	public function mobile( $data , $userInfo )
	{
		$this -> setSource( 'mobile' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );
		$this -> checkLianpiao();
		$this -> checkPihao();
		$this -> checkPihaoTime();
		$this -> checkTravel();
		$this -> checkZuhesp();
		$yudingData = $this -> checkYuding();
		$operaData = $this->opera($yudingData);
		if( !$operaData ){
			throw new LogicException('预订失败，请稍后重试');
		}
		$this->sendCheck( $yudingData['data'] );
		$this->sendNewCheck( $yudingData['data'] );
		$this->sms();
		//$this->sendTemplate( $yudingData['data'] );
		$this->addRecord();
		$this->clear();
	}

	public function admin( $data , $userInfo )
	{
		$this -> setSource( 'admin' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );
		$this -> checkLianpiao();
		$this -> checkPihao();
		$this -> checkPihaoTime();
		$this -> checkTravel();
		$this -> checkZuhesp();
		$yudingData = $this -> checkYuding();
		$operaData = $this->opera($yudingData);
		if( !$operaData ){
			throw new LogicException('预订失败，请稍后重试');
		}
		$this->sendCheck( $yudingData['data'] );
		$this->sendNewCheck( $yudingData['data'] );
		$this->sms();
		$this->addRecord();
		$this->clear();
	}

	/*
	 * 支付订单封装
	 */
	public function payTicket($data,$userInfo){
		$this -> setSource( 'mobile' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );
		$this -> checkLianpiao();
		$this -> checkPihao();
		$this -> checkPihaoTime();
		$this -> checkTravel();
		$this -> checkZuhesp();
		return  $this -> checkYuding();
	}


	/*
	 * 修复数据预留接口
	 */
	public function repareDate()
	{
		//
	}

	/*
	 * 执行订单操作
	 * array $data 结构给 ['flag'=>操作标示(updata,insert),'data'=>订单数据封装]
	 * 可以单独调用该模块
	 */
	public function opera( $data ){

		empty($this->data) && $this->setData( $data['data'] );

		if($data['flag'] == 'update'){
			$res = db('yuding')->where( 'id',$this->operaId )->update($data['data']);
			if($res >= 0){
				return true;
			}
		}
		if($data['flag'] == 'insert'){
			$res = db('yuding')->insertGetId($data['data']);
			if($res >= 0){
				$this->setOperaId( $res );
				return true;
			}
		}

		return false;
	}

	/*
	 * 发送订单到API平台
	 * array $data 订单数据
	 * int   $product  验票产品id
	 * string $source  操作来源
	 * 单独调用该模块，需要传递订单数据和验票产品id，
	 */
	public function sendCheck( $data , $product = null ,$source = null){
		empty($product) && empty($this->travelResult) &&  $this->getTravel();
		empty($this->operaId) && $this->setOperaId( $data['id'] );

		$flag = 1;  //1 单日景区订单，2 多日景区订单
		$source = $this->source;

		//port_yuding数据封装
		$orderInfo['dsOrderCode']   = $data['prize_coupon_code'];
		$orderInfo['sign']          = "c32de88944cfda16c8bb0119fe3e1b56";
		$orderInfo['yuding_id']     = $this->operaId;
		$orderInfo['productId']     = $product ? $product : $this->travelResult['api_id'];
		$orderInfo['cradNo']        = $data['shenfenzheng'];
		$orderInfo['name']          = $data['worker'];
		$orderInfo['phone']         = $data['phone'];
		$orderInfo['playDate']      = $data['yudingtime'];
		if($data['yudingtime'] <> $data['endyudingtime']){
			$orderInfo['endPlayDate']      = $data['endyudingtime'];
			$flag = 2;
		}
		$orderInfo['travel_id']          = $data['travel_id'];
		$orderInfo['jqname']        = $data ['jqname'];
		$orderInfo['lianpiaono']    = $data['lianpiaono'];
		$orderInfo['addtime']       = date('Y-m-d H:i:s');

		//api发送订单数据封装
		$order['downstreamOrderCode']=$orderInfo['dsOrderCode'];
		$order['cradNo']=$data['shenfenzheng'];
		$order['name']=$data['worker'];
		$order['phone']=$data['phone'];
		$orderAll[]=$order;
		//发送验票订单
		$port = \api\CheckApi::getinstance();
		if($flag == 1){
			$flag_sendResult = $port->sendAPIOrder($this->travelResult['api_id'],$data['yudingtime'],$orderAll,1,$source);
		}elseif($flag == 2){
			$flag_sendResult = $port->sendFreeOrder($this->travelResult['api_id'],$data['yudingtime'],$data['endyudingtime'],$orderAll,1,$source);
		}
		//发送结果
		$orderInfo['description'] = $port->result['description'];
		$orderInfo['code'] =  $port->result['code'];

		//检查订单在port_yuding中是否存在
		$checkIs = db('port_yuding')->where('yuding_id',$this->operaId)->field('id,dsOrderCode')->find();

		$dataAll[]=$orderInfo;
		db('port_yuding')->insertAll($dataAll);

	}

	/*
	 * 发送微信模板
	 * param $data array    订单数据
	 * 依赖：单独使用该模块需要设置setUserInfo(),获取openid
	 */
	public function sendTemplate( $data ){
		empty($this->travelResult) && $this->getTravel();
		//微信提醒开始
		$content_wx="恭喜！".$data['worker']."\t成功预订\t".$data['jqname']."\t景区\n\n点我查看详情！\n\n";
		if($this->travelResult['enterpark']==""){
			$content_wx.="入园换票提醒:持整本联票和本人身份证原件换票入园";
		}else{
			$content_wx.="入园换票提醒:".strip_tags($this->travelResult['enterpark']);
		}
		$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd16d0ae5fae8f790&redirect_uri=http://www.chaozhiwang.cn/index.php?m=Qxinfo&response_type=code&scope=snsapi_base&state=orderId_".$this->operaId."#wechat_redirect";
		$data_wx['touser'] = $this->userInfo['open_id'];
		$data_wx['template_id']='nrw7ISr-IkLRd8v4Z5WwdUHi_qcWNCOYVgI8HyWrOWA';
		$data_wx['url']=$url;
		$data_wx['topcolor']='#FF0000';
		$data_wx['data']['first']=array('value'=>$content_wx,'color'=>'#173177');
		$data_wx['data']['type']=array('value'=>'出游日期','color'=>'#173177');
		$data_wx['data']['name']=array('value'=>$data['yudingtime'],'color'=>'#173177');
		$data_wx['data']['productType']=array('value'=>'景区','color'=>'#173177');
		$data_wx['data']['serviceName']=array('value'=>$data['jqname'],'color'=>'#173177');
		$data_wx['data']['time']=array('value'=>$data ['addtime'],'color'=>'#173177');
		$data_wx['data']['remark']=array('value'=>'客服电话: 400-000-0445','color'=>'#173177');
		$flag = Wechat::app()->notice->send($data_wx);
		//微信提醒结束
	}

	/**
	 * 操作记录日志
	 * 向记录表中添加记录
	 */
	public function addRecord()
	{
		$data = array();
		$data[ 'uid' ] = $this -> userInfo[ 'uid' ];
		$data[ 'username' ] = !empty( $this -> userInfo[ 'nickname' ] ) ? $this -> userInfo[ 'nickname' ] : $this -> userInfo[ 'phone' ];
		$data[ 'content' ] = "预定景区 {$this->travelResult['title']}({$this->travelResult['aid']})  联票号为:{$this->lianpiaoResult['lianpiaono']} 出游时间： ( {$this->data['date_str']} )";
		$data[ 'buid' ] = $this -> lianpiaoResult[ 'id' ];
		$data[ 'buname' ] = $this -> lianpiaoResult[ 'username' ];
		$data[ 'rtime' ] = date( 'Y-m-d H:i:s' );
		$data[ 'source' ] = $this -> sourceMsg;
		$data[ 'ip' ] = request()->ip();
		$data[ 'wxuserid' ] = isset( $this -> userInfo[ 'open_id' ] ) ? $this -> userInfo[ 'open_id' ] : '';
		db( 'record' ) -> insert( $data );
	}


	public function sms()
	{
		//发送短信开始
		//if ( $this->travelResult[ 'isduanxin' ] == '10' ) {
			$send_data = array();
			$send_data[ 'name' ] = $this->lianpiaoResult[ 'username' ];
			$send_data[ 'jqname' ] = $this->travelResult[ 'title' ];
			$send_data[ 'yudingtime' ] = $this->data[ 'date_str' ];
			$send_data[ 'beizhu' ] = $this->travelResult[ 'duanxin_beizhu' ];
			$msg = Msg::getinstance();
			$msg->sendSMS( $this->lianpiaoResult[ 'phone' ] , $send_data , 6 );
		//}
	}

	public function sendNewCheck( $data ){
		$data = array(
			'order_id'		=>	$data['prize_coupon_code'],
			'sign'			=>	'34d4afa5dfa71fbc0e363ca605d02065',
			'book_time'		=>	strtotime($data['yudingtime']),
			'book_end_time'=>	strtotime($data['endyudingtime']),
			'sp_id'			=>	$data['travel_id'],
			'idcard'		=>	$data['shenfenzheng'],
			'phone'			=>	$data['phone'],
			'traveler_name'	=>	$data['worker'],
			'create_time'	=>	time(),
		);
		$checkTicketModel = new CheckTicket();
		$res = $checkTicketModel->insert($data);
	}



}